package com.elite.groovy.callback

import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat
/**
 *
 * @Title: apiLoginToken
 *
 */

public class apiLoginToken implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiLoginToken.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        String inData = "";
        JSONObject outData = JSONObject.parseObject("{\"code\":0,\"message\":\"token检查未知错误\",\"value\":null}");
        String getMethod = request.getMethod();
        log.debug("apiLoginToken getMethod:" + getMethod);

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("apiLoginToken Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("apiLoginToken Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }
        log.debug("***原始GET请求参数:" + mapParam.toString());

        // 请求参数信息
        if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("***原始POST请求参数:" + inData);
        }

        if (!getMethod.equals("POST")) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData.toString();
        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            // 获取嵌入传递的参数
            String accToken = "";
            String sysFlag = "";
            if (KHUtil.isNull(inData)) {
                accToken = mapParam.get("token");
                sysFlag = mapParam.get("sysFlag");
            } else {
                JSONObject inDataJson = JSONObject.parseObject(inData);
                accToken = inDataJson.getString("token");
                sysFlag = inDataJson.getString("sysFlag");
            }
            log.debug("获取调用参数Token:" + accToken + " sysFlag:" + sysFlag);

            if (KHUtil.isNull(accToken)) {
                outData.put("code", -1);
                outData.put("message", "获取Token信息错误，接口调用accToken：" + accToken);
                return outData.toString();
            }

            // 检查当前登录用户在系统中是否有效(人&组&关系)
            String checkSQL = '''Select R1.Staff_Id id,
                                   R1.Staffname as name,
                                   r2.AGENT_ID as agentId,
                                   R2.Loginname as loginName,
                                   '' as epid,
                                   '' as epidDbPool,
                                   LOGINKEY as remoteKey,
                                   r1.headImg,
                                   r1.issupervisor,
                                   rolegroupType,
                                   R1.Logintime as loginTime,
                                   R1.Rolegroup_Id,
                                   R1.Clientip
                              From Webloginlist R1
                              Left Join Staff R2
                                On R1.Staff_Id = R2.Staff_Id
                              Left Join Rolegroup R3
                                On R1.Rolegroup_Id = R3.Rolegroup_Id
                             Where R1.Loginuuid = ?''';
            List<Map<String, Object>> checkSQLResult = jt.queryForList(checkSQL, accToken);
            log.debug("检查当前登录用户在系统中是否有效-结果:" + checkSQLResult.toString());

            // 如果人员信息不存在-新建
            if (checkSQLResult.size() > 0) {
                outData.put("code", 1);
                outData.put("message", "Token检查完成");

                JSONObject valueJ = new JSONObject();
                JSONArray projects = JSONArray.parseArray("[{\"id\":\"default\",\"name\":\"默认项目\",\"token\":\"" + accToken + "\",\"ordIndex\":0,\"groupId\":\"" + KHUtil.GetMapV(checkSQLResult.get(0), "Rolegroup_Id") + "\",\"groupName\":\"######\",\"roles\":[{\"id\":\"###DEV\",\"name\":\"项目实施\"}]}]");
                JSONObject extra = JSONObject.parseObject("{\"STRINGFIELD1\":\"\"}");
                valueJ.put("id", KHUtil.GetMapV(checkSQLResult.get(0), "id"));
                valueJ.put("name", KHUtil.GetMapV(checkSQLResult.get(0), "name"));
                valueJ.put("agentId", KHUtil.GetMapV(checkSQLResult.get(0), "agentId"));
                valueJ.put("loginName", KHUtil.GetMapV(checkSQLResult.get(0), "loginName"));
                valueJ.put("epid", KHUtil.GetMapV(checkSQLResult.get(0), "epid"));
                valueJ.put("epidDbPool", KHUtil.GetMapV(checkSQLResult.get(0), "epidDbPool"));
                valueJ.put("remoteKey", KHUtil.GetMapV(checkSQLResult.get(0), "remoteKey"));
                valueJ.put("headImg", KHUtil.GetMapV(checkSQLResult.get(0), "headImg"));
                valueJ.put("issupervisor", KHUtil.GetMapV(checkSQLResult.get(0), "issupervisor"));
                valueJ.put("rolegroupType", KHUtil.GetMapV(checkSQLResult.get(0), "rolegroupType"));
                valueJ.put("loginTime", dateToStamp(KHUtil.GetMapV(checkSQLResult.get(0), "loginTime")));
                valueJ.put("Rolegroup_Id", KHUtil.GetMapV(checkSQLResult.get(0), "Rolegroup_Id"));
                valueJ.put("Clientip", KHUtil.GetMapV(checkSQLResult.get(0), "Clientip"));
                valueJ.put("extra", extra);
                valueJ.put("projects", projects);

                valueJ.put("epidSql", "");

                outData.put("value", valueJ);

            }

            log.debug("登录认证返回结果：" + outData.toString());

        } catch (Exception e) {
            outData.put("code", -2);
            outData.put("message", "HTTP请求调用错误(" + apiLoginToken + "),请稍后再试!");
            log.error(outData, e);

        }/* finally {
            LogToDB.toDB(eliteBean, "dataSource", "登录认证-对接单点登录", "apiLoginToken", inData, outData.toString(), String.valueOf(System.currentTimeMillis() - startTime), "-");
        }*/
        return outData.toString();

    }
    public static String dateToStamp(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (Exception e) {
            log.error("dateToStamp Exception:" + e.getMessage());
        }

        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

}